import * as XLSX from 'xlsx'
import { readFile} from "../../utils/xlsx";
import {batchAddRollCallBasicShuttleData,batchAddRollCallBasicShuttleSeatData,batchAddRollCallBasicShuttleStopData} from "../../request/api/basicData";
import Linq from 'linq'

let shuttleRowIds = [];
//导入
export const handleUploadChange = async (file) => {
  return new Promise(async resolve => {
    let dataBinary = await readFile(file.raw);
    let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true })
    let workSheet = workBook.Sheets[workBook.SheetNames[0]]
    const data = XLSX.utils.sheet_to_json(workSheet);
    const school = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SCHOOL : window.webConfig.webSchool;
    let list = [];
    let fields = {
        'shuttle_no': '点名班车号',
        'shuttle_name': '点名班车名',
        'shuttle_type': '班车类型',
        'effective_date_begin': '有效日期起',
        'effective_date_end': '有效日期止',
        'direction': '方向',
        'first_departure_time': '始发时间',
        'shuttles': '售票班车名串',
        'line_name': '线路名',
        'first_stop_name': '起点',
        'last_stop_name': '终点',
        'seat_count': '客座数',
        'vehicle_no': '车牌号码',
        'driver_name': '司机姓名',
        'caretaker_name': '照管员名',
        'rollcall_admin_name': '点名管理人名',
        'stop_no': '乘车点编号',
        'stop_name': '乘车点名称',
        'departure_time': '发车时间',
        'seat_no': '实际座位号',
        'passenger_name': '乘车人姓名',
        'idcard_type': '乘车人证件类型',
        'idcard_no': '乘车人证件号',
        'school_no': '站点编号',
        'school_name': '站点名称',
        'school_longitude': '站点经度',
        'school_latitude': '站点纬度',
        'school_departure_time': '站点时间',
        'class_': '班级',
        'parents_name': '购票人姓名',
        'parents_phone': '购票人手机',
        'longitude': '乘车点经度',
        'latitude': '乘车点纬度',
        'path_type': '乘车点类型',
        'parents_take_children_type_no': '下车接送方式编号',
        'parents_take_children_type_name': '下车接送方式名称',
        'order_no': '订单号'
      },
      shuttlesObj = {},
      stopsObj = {},
      seatList = [];
    console.log('导入数据',data);
    data.forEach(item => {
      //没有班车信息也没有座位信息的跳过
      // if ((!item['点名班车号'] || !item['方向']) && (!item['乘车人姓名'] || !item['实际座位号'])) return;
      if ((!item['点名班车号'] || !item['方向']) &&  !item['实际座位号']) return;
      let shuttleObj = {is_used: true},
        stopObj = {}, //站点信息
        schoolStopObj = {}, // 站点信息
        seatObj = {state: '未点名'}; // 座位信息
      // 遍历字段

      for (let field_id in fields) {
        if (fields.hasOwnProperty(field_id)){
          let field_name = fields[field_id],
            value = (item[field_name] || '') + '';
          // 班车信息
          if (['shuttle_no','shuttle_name','shuttle_type','effective_date_begin','effective_date_end','direction','first_departure_time','shuttles','line_name','first_stop_name','last_stop_name','seat_count','vehicle_no','driver_name','caretaker_name','rollcall_admin_name'].includes(field_id)) {
            shuttleObj[field_id] = value;
          }
          // 座位乘车人信息
          if (['stop_no','stop_name','seat_no','passenger_name','idcard_type','idcard_no','school_name','class_','parents_name','parents_phone','parents_take_children_type_no','parents_take_children_type_name','order_no'].includes(field_id)) {
            if (field_id === 'seat_no') value = value ? Number(value) : null;
            seatObj[field_id] = value;
          }
          // 站点信息
          if (['stop_no','stop_name','departure_time','latitude','longitude','path_type'].includes(field_id)) {
            stopObj[field_id] = value;
            if (['latitude','longitude',].includes(field_id)) {
              stopObj[field_id] = value ? value : null;
            }
          }
          // 站点信息
          if (['school_no','school_name','school_departure_time','school_longitude','school_latitude'].includes(field_id)){
            let contrast = {
              school_no: 'stop_no',
              school_name: 'stop_name',
              school_departure_time: 'departure_time',
              school_longitude: 'longitude',
              school_latitude: 'latitude'
            }
            schoolStopObj[contrast[field_id]] = value;
            if (['school_longitude','school_latitude',].includes(field_id)) {
              schoolStopObj[contrast[field_id]] = value ? value : null;
            }
          }
        }

      }
      // 下车接送方式名称对应id
      if (seatObj.parents_take_children_type_name && !seatObj.parents_take_children_type_no) {
        seatObj.parents_take_children_type_no = seatObj.parents_take_children_type_name === '自行回家' ? 'js001'
          : seatObj.parents_take_children_type_name === '购票人接送' ? 'js002'
            : '';
      }

      let {shuttle_no,direction } = shuttleObj,
        {stop_no} = stopObj,
        school_stop_no = schoolStopObj.stop_no;

      // 乘车人座位信息没有传入点名班车信息，默认传入上一个点名班车
      if (!shuttle_no || !direction){
        let keys = Object.keys(shuttlesObj),
          lastShuttle = shuttlesObj[keys[keys.length-1]];
        shuttle_no = lastShuttle?.shuttle_no;
        direction = lastShuttle?.direction;
      }
      seatObj.shuttle_id = shuttle_no + ',' + direction;
      stopObj.shuttle_id = shuttle_no + ',' + direction;
      schoolStopObj.shuttle_id = shuttle_no + ',' + direction;
      // 储存点名班车信息(班车号+ 方向组成唯一)
      if (shuttle_no && !shuttlesObj[shuttle_no+direction]){ shuttlesObj[shuttle_no+direction] = shuttleObj}
      // 储存点名班车站点信息(班车号+ 方向+ 站点号 组成唯一)
      if (shuttle_no && stop_no && !stopsObj[shuttle_no+direction+stop_no])stopsObj[shuttle_no+direction+stop_no] = stopObj
      // 储存点名班车站点信息（班车号 + 方向 + 站点号 组成唯一）

      if (shuttle_no && school_stop_no && !stopsObj[shuttle_no+direction+school_stop_no]){
        schoolStopObj.path_type = '站点';
        stopsObj[shuttle_no+direction+school_stop_no] = schoolStopObj
      }
      seatList.push(seatObj)

    });
    let errmsg = ''

    if (!Object.keys(shuttlesObj).length && seatList.length) {
      errmsg = '导入数据中没有找到点名班车信息，请重新上传'
    }
    if (!Object.keys(shuttlesObj).length && !seatList.length) {
      errmsg = '导入数据不能为空'
    }

    if (errmsg) {
      ElMessage({
        type: 'warning',
        message: errmsg
      });
      return;
    }
    let isRepeat = false;
    await beforeUpdateSeat(seatList).then(res =>{
      if (res.length > 0){
        isRepeat = true;
        console.log(res);
        let err = [];
        res.forEach(item => {
          let arr = item.key.split(',');
          err.push(`点名班车号：${arr[0]}，方向：${arr[1]}，座位号：${arr[2]}，<br/>\n`)
        });
        errmsg = '座位表导入有重复，请检查：<br/>\n' + err.join('');
        ElMessageBox.confirm(errmsg,'提示',{
          'confirmButtonText': '确定',
          showCancelButton: false,
          dangerouslyUseHTMLString:true, // 注意此属性
        })
      }
    })
    if (isRepeat) return;
    const loadingInstance = ElLoading.service({
      text: '正在导入中，请耐心等待',
      background: '#00000080'
    });

    let shuttleList = Object.values(shuttlesObj)
    batchAddRollCallBasicShuttleData(shuttleList).then(res =>{
      if (res.errcode != 0) return;
      let resData = res.row;
      shuttleRowIds = resData;

      let pms = [];
      // 更新座位信息
      if (seatList.length) pms.push(updateSeatData(resData,seatList))
      if (Object.keys(stopsObj).length) pms.push(updateStopData(resData,stopsObj))

      if (pms.length) {
        Promise.all(pms).then(res =>{
          loadingInstance.close();
          let total = res[0].total || 0
          ElMessageBox.alert(`本次导入${total}条数据`, '导入成功', {
            confirmButtonText: '确定',
          });
          resolve();
        })
      }else {
        loadingInstance.close();
        let total = res.total || 0
        ElMessageBox.alert(`本次导入${total}条数据`, '导入成功', {
          confirmButtonText: '确定',
        });
        resolve();
      }

    })

  })

}

const beforeUpdateSeat = function (seatList) {
  return new Promise(resolve => {
    let queryResult = Linq.from(seatList)
      .groupBy(
        x => [x.shuttle_id,x.seat_no].join(','),  //按班车名，方向，座位号分组
        x => x // 选择每个分组的元素
      )
      .select(  //
        function (group) {
          return {
            key: group.key(),
            source: group.getSource(),
          }
        }
      )
      .where(x => x.source.length > 1)
      .toArray();
    resolve(queryResult);
  })
}

const updateSeatData = function (resData,seatList) {
  return new Promise(resolve => {
    seatList.forEach(item =>{
      let {shuttle_id} = item;
      let arr = shuttle_id?.split(','),
        rowData = arr.length && resData.find(item => item.shuttle_no === arr[0] && item.direction === arr[1]);
      if (rowData) item.shuttle_id = rowData.row_id;
    });
    batchAddRollCallBasicShuttleSeatData(seatList).then(res =>{
      if (res.errcode != 0) return;
      resolve(res)
    })
  })
};

const updateStopData = function (resData,stopsObj) {
  return new Promise(resolve => {
    let stopList = [];
    for (let key in stopsObj){
      if (stopsObj.hasOwnProperty(key)){
        let item = stopsObj[key],
          arr = item.shuttle_id?.split(','),
          rowData = arr.length && resData.find(item => item.shuttle_no === arr[0] && item.direction === arr[1]);
        if (rowData) item.shuttle_id = rowData.row_id;
        stopList.push(item);
      }
    }
    batchAddRollCallBasicShuttleStopData(stopList).then(res =>{
      if (res.errcode != 0 ) return;
      resolve();
    })
  })
}

